﻿using System;
using System.Collections.Generic;
using DB_EntityFramework;
using DB_EntityFramework.UserManaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL.Managers
{
    public class UserManager
    {
        UserContext ctx = new UserContext();

        public List<User> GetAll()
        {
            List<User> result = new List<User>();

            result = ctx.Users.ToList() ?? result;

            return result;
        }

        public List<Employee> GetEmployees()
        {
            List<Employee> result = new List<Employee>();

            result = ctx.Emploees.ToList() ?? result;

            return result;
        }

        public Employee GetEmployeeById(int id)
        {
            return ctx.Emploees.FirstOrDefault(u => u.Id == id);
        }

        public User GetById(int id)
        {
            return ctx.Users.SingleOrDefault(u => u.Id == id);
        }

        public void Edit(User user)
        {
            //var dbUser = this.GetById(user.Id);
            //dbUser.Name = user.Name;
            ctx.Entry(user).State = System.Data.Entity.EntityState.Modified;//.ChangeObjectState(stud, System.Data.EntityState.Modified);
            //ctx.ChangeTracker.
            ctx.SaveChanges();
        }
        public void Edit(Employee user)
        {
            ctx.Entry(user).State = System.Data.Entity.EntityState.Modified;
            ctx.SaveChanges();
        }
        public void Insert(Employee user)
        {
            user.Id = -1;
            this.ctx.Emploees.Add(user);
            this.ctx.SaveChanges();
        }

        public void Delete(Employer user)
        {
            ctx.Emploers.Remove(user);
            ctx.SaveChanges();
        }
        public void Delete(Employee user)
        {
            Employee e = ctx.Emploees.FirstOrDefault(u => u.Id == user.Id);
            ctx.Emploees.Remove(e);
            ctx.SaveChanges();
        }

        #region Security
        public string[] GetUserRoles(string login)
        {

            var user = ctx.Users.FirstOrDefault(u => u.Login == login);
            user.Roles = ctx.Entry(user).Collection(u => u.Roles).Query().ToList();
            if (user != null)
            {
                //all users should have at least one role attached
                return user.Roles.Select(r => r.Name).ToArray();
            }
            return new string[] { };
        }

        public bool IsValid(string login, string password)
        {
            var user = ctx.Users.FirstOrDefault(u => u.Login == login && u.Password == password);
            return user != null;
        }
        #endregion
                
    }
}
